package com.android.shuttle.chart.xlchart;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Paint.Style;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;

import org.xclcharts.chart.CustomLineData;
import org.xclcharts.chart.PointD;
import org.xclcharts.chart.SplineChart;
import org.xclcharts.chart.SplineData;
import org.xclcharts.common.DensityUtil;
import org.xclcharts.common.IFormatterTextCallBack;
import org.xclcharts.event.click.PointPosition;
import org.xclcharts.renderer.XEnum;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class GridLineView extends DemoView {
    private String TAG = "SplineChart03View";
    private SplineChart chart = new SplineChart();
    //分类轴标签集合
    private LinkedList<String> labels = new LinkedList<String>();
    private LinkedList<SplineData> chartData = new LinkedList<SplineData>();

    private Paint mPaintTooltips = new Paint(Paint.ANTI_ALIAS_FLAG);

    //setCategoryAxisCustomLines
    // splinechart支持横向和竖向定制线
    private List<CustomLineData> mXCustomLineDataset = new ArrayList<CustomLineData>();
    private List<CustomLineData> mYCustomLineDataset = new ArrayList<CustomLineData>();

    private AxisMode currentMode = AxisMode.XY;

    private List<PointD> xyDatas = new ArrayList<>();
    private SplineData xySplineData = new SplineData();
    private List<PointD> xzDatas = new ArrayList<>();
    private SplineData xzSplineData = new SplineData();
    private List<PointD> yzDatas = new ArrayList<>();
    private SplineData yzSplineData = new SplineData();


    public GridLineView(Context context) {
        this(context, null);
    }

    public GridLineView(Context context, AttributeSet attrs) {
        this(context, attrs, -1);
    }

    public GridLineView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initView();
    }

    private void initView() {
        // x轴标签轴
        initXaxisLabel();
        // x，y 原点线
        init0Line();
        // 配置图标信息
        initChartConfig();
        initSplineData();
        //綁定手势滑动事件
        this.bindTouch(this, chart);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        //图所占范围大小
        chart.setChartRange(w, h);
    }

    @Override
    public void render(Canvas canvas) {
        try {
            chart.render(canvas);
        } catch (Exception e) {
            Log.e(TAG, e.toString());
        }
    }

    /**
     * 初始化chart配置信息
     */
    private void initChartConfig() {
        try {
            //设置绘图区默认缩进px值,留置空间显示Axis,Axistitle....
            int[] ltrb = getBarLnDefaultSpadding();
            chart.setPadding(ltrb[0], ltrb[1], ltrb[2], ltrb[3]);
            //显示边框
            //chart.showRoundBorder();
            chart.hideBorder();
            //手势滑动的方向-horizontal -vertical - both
            chart.setPlotPanMode(XEnum.PanMode.FREE);
            DisplayMetrics dm = getResources().getDisplayMetrics();
            int screenWidth = dm.widthPixels;
            int screenHeight = dm.heightPixels;

            //chart.setTranslateXY(screenWidth / 2 - ltrb[0], screenHeight / 2 - ltrb[1]);
            //数据源
            chart.setCategories(labels);
            chart.setDataSource(chartData);
            //坐标系
            //数据轴最大值
            chart.getDataAxis().setAxisMax(1000);
            chart.getDataAxis().setAxisMin(-1000);
            //数据轴刻度间隔
            chart.getDataAxis().setAxisSteps(100);
            chart.setCustomLines(mYCustomLineDataset); //y轴
            chart.getCategoryAxis().setAxisSteps(100);
            // x y 轴的位置
            //chart.setCategoryAxisLocation(XEnum.AxisLocation.HORIZONTAL_CENTER);
            chart.setDataAxisLocation(XEnum.AxisLocation.LEFT);
            //chart.setAxesClosed(true);
            //标签轴最大值
            chart.setCategoryAxisMax(100);
            //标签轴最小值
            chart.setCategoryAxisMin(0);
            //chart.setCustomLines(mXCustomLineDataset); //y轴
            chart.setCategoryAxisCustomLines(mXCustomLineDataset); //x轴
            //设置图的背景色
            chart.setApplyBackgroundColor(true);
            //chart.setBackgroundColor( Color.rgb(212, 194, 129) );
            chart.setBackgroundColor(Color.WHITE);
            //chart.getBorder().setBorderLineColor(Color.rgb(179, 147, 197));
            //调轴线与网络线风格
            chart.getCategoryAxis().hideTickMarks();
            chart.getCategoryAxis().hideAxisLine();
            //chart.getCategoryAxis().hideAxisLabels();
            chart.getDataAxis().hideAxisLine();
            chart.getDataAxis().hideTickMarks();
            //hart.getDataAxis().hideAxisLabels();
            // gridline
            chart.getPlotGrid().showVerticalLines();
            chart.getPlotGrid().showHorizontalLines();
            //chart.getCategoryAxis().hideAxisLabels();
            //chart.getDataAxis().hideAxisLabels();
            //chart.hideTopAxis();
            //chart.hideRightAxis();
            chart.getPlotGrid().getHorizontalLinePaint().setColor(Color.rgb(179, 147, 197));
            chart.getCategoryAxis().getAxisPaint().setColor(
                    chart.getPlotGrid().getHorizontalLinePaint().getColor());
            chart.getCategoryAxis().getAxisPaint().setStrokeWidth(
                    chart.getPlotGrid().getHorizontalLinePaint().getStrokeWidth());
            //定义交叉点标签显示格式,特别备注,因曲线图的特殊性，所以返回格式为:  x值,y值
            //请自行分析定制
            chart.setDotLabelFormatter(new IFormatterTextCallBack() {

                @Override
                public String textFormatter(String value) {
                    // TODO Auto-generated method stub
                    String label = "[" + value + "]";
                    return (label);
                }

            });
            //标题
            //chart.setTitle("Spline Chart");
            //chart.addSubtitle("(XCL-Charts Demo)");
            //激活点击监听
            chart.ActiveListenItemClick();
            //为了让触发更灵敏，可以扩大5px的点击监听范围
            chart.extPointClickRange(20);
            chart.showClikedFocus();
            //显示平滑曲线
            chart.setCrurveLineStyle(XEnum.CrurveLineStyle.BEZIERCURVE);
            //图例显示在正下方
            //chart.getPlotLegend().setVerticalAlign(XEnum.VerticalAlign.BOTTOM);
            //chart.getPlotLegend().setHorizontalAlign(XEnum.HorizontalAlign.CENTER);
            chart.getPlotLegend().hide();
            chart.enabledCtlPanRange();

            int margin = DensityUtil.dip2px(getContext(), 20);
            chart.setXTickMarksOffsetMargin(margin);
            chart.setYTickMarksOffsetMargin(margin);
            chart.disabledCtlPanRange();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Log.e(TAG, e.toString());
        }
    }

    /**
     * 初始化 x 轴 grid 标签数值
     */
    private void initXaxisLabel() {
        for (int i = -1000; i <= 1000; ) {
            labels.add("" + i);
            i += 100;
        }
    }

    /**
     * 初始化x,y 0 线，即在 x = 0, y = 0 的位置上分别画条线
     */
    private void init0Line() {
        // y 轴竖线为 xStep 的一半
        CustomLineData yIndicatorAxis = new CustomLineData("", 50d, Color.rgb(35, 172, 57), 5);
        yIndicatorAxis.setLabelVerticalAlign(XEnum.VerticalAlign.MIDDLE);
        mXCustomLineDataset.add(yIndicatorAxis);
        // x 轴竖线
        CustomLineData xIndicatorAxis = new CustomLineData("", 0d, Color.rgb(69, 181, 248), 5);
        xIndicatorAxis.setLabelHorizontalPostion(Align.CENTER);
        mYCustomLineDataset.add(xIndicatorAxis);
    }

    private void initSplineData() {
        xySplineData.setLabelVisible(false);
        xySplineData.setDotRadius(4);
        xySplineData.getLinePaint().setColor(Color.GREEN);

        yzSplineData.setLabelVisible(false);
        yzSplineData.setDotRadius(4);
        yzSplineData.getLinePaint().setColor(Color.RED);

        xzSplineData.setLabelVisible(false);
        xzSplineData.setDotRadius(4);
        xzSplineData.getLinePaint().setColor(Color.BLACK);
    }

    /**
     * 添加单个数据
     *
     * @param locateD
     */
    public void addSingleData(LocateD locateD) {
        xzDatas.add(new PointD(locateD.getX(), locateD.getZ()));
        yzDatas.add(new PointD(locateD.getY(), locateD.getZ()));
        xyDatas.add(new PointD(locateD.getX(), locateD.getY()));
        updateDataSet();
    }

    /**
     * 批量添加数据
     *
     * @param locateDList
     */
    public void addDataSet(List<LocateD> locateDList) {
        if (locateDList == null) {
            return;
        }
        for (LocateD locateD : locateDList) {
            xzDatas.add(new PointD(locateD.getX(), locateD.getZ()));
            yzDatas.add(new PointD(locateD.getY(), locateD.getZ()));
            xyDatas.add(new PointD(locateD.getX(), locateD.getY()));
        }
        xySplineData.setLineDataSet(xyDatas);


        yzSplineData.setLineDataSet(yzDatas);


        xzSplineData.setLineDataSet(xzDatas);

        updateDataSet();
    }

    public void updateDataSet() {
        chartData.clear();
        switch (currentMode) {
            case XY:
                Log.e("dataset", xyDatas.toString());
                xySplineData.setLineDataSet(xyDatas);
                chartData.add(xySplineData);
                break;
            case YZ:
                Log.e("dataset", yzDatas.toString());
                yzSplineData.setLineDataSet(yzDatas);
                chartData.add(yzSplineData);
                break;
            case XZ:
                Log.e("dataset", xzDatas.toString());
                xzSplineData.setLineDataSet(xzDatas);
                chartData.add(xzSplineData);
                break;
            default:
                break;
        }
        invalidate();
    }

    public void changeAxisMode(AxisMode currentMode) {
        this.currentMode = currentMode;
        updateDataSet();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        super.onTouchEvent(event);
        if (event.getAction() == MotionEvent.ACTION_UP) {
            triggerClick(event.getX(), event.getY());
        }
        return true;
    }


    //触发监听
    private void triggerClick(float x, float y) {
        if (!chart.getListenItemClickStatus()) return;

        PointPosition record = chart.getPositionRecord(x, y);
        if (null == record) return;

        if (record.getDataID() >= chartData.size()) return;
        SplineData lData = chartData.get(record.getDataID());
        List<PointD> linePoint = lData.getLineDataSet();
        int pos = record.getDataChildID();
        int i = 0;
        Iterator it = linePoint.iterator();
        while (it.hasNext()) {
            PointD entry = (PointD) it.next();

            if (pos == i) {
                Double xValue = entry.x;
                Double yValue = entry.y;
                x = (float) entry.x;
                y = (float) entry.y;

                float r = record.getRadius();
                chart.showFocusPointF(record.getPosition(), r + r * 0.8f);
                chart.getFocusPaint().setStyle(Style.FILL);
                chart.getFocusPaint().setStrokeWidth(3);
                if (record.getDataID() >= 2) {
                    chart.getFocusPaint().setColor(Color.BLUE);
                } else {
                    chart.getFocusPaint().setColor(Color.RED);
                }
                //在点击处显示tooltip
                mPaintTooltips.setColor(Color.WHITE);
                mPaintTooltips.setTextSize(20);

                chart.getToolTip().setInfoStyle(XEnum.DyInfoStyle.CAPROUNDRECT);
                chart.getToolTip().setAlign(Align.CENTER);
                chart.getToolTip().setMargin(20);
                chart.getToolTip().getBackgroundPaint().setColor(Color.GRAY);
                chart.getToolTip().getBorderPaint().setColor(Color.BLACK);

                chart.getToolTip().setCurrentXY(x, y + 10);
                chart.getToolTip().addToolTip(
                        "(" + Double.toString(xValue) + "," + Double.toString(yValue) + ")", mPaintTooltips);
                this.invalidate();

                break;
            }
            i++;
        }//end while

    }

}
